<template>
	<el-input v-model="filterText" input-style="border-radius: 15px !important; " placeholder="请输入您要查询的节点" />

	<div class="list_div">
		<el-tree
			ref="treeRef"
			class="filter-tree"
			style="margin-top: 20px"
			node-key="id"
			accordion
			:data="data"
			:props="defaultProps"
			:filter-node-method="filterNode"
			lazy
			:load="loadChain"
			@node-click="changeChain"
			:current-node-key="firstNode"
		/>
	</div>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted } from 'vue';
import { ElTree } from 'element-plus';
import { getList, getDetail } from '/@/api/chain/index';

const props = defineProps({
	hasAll: {
		default:false
	}
})

const emit = defineEmits(['changeChain']);

interface Tree {
	[key: string]: any;
}

const filterText = ref('');
const treeRef = ref<InstanceType<typeof ElTree>>();

const defaultProps = {
	children: 'children',
	label: 'chain_name',
	isLeaf: 'isLeaf',
};

watch(filterText, (val) => {
	treeRef.value!.filter(val);
});

const filterNode = (value: string, data: Tree) => {
	if (!value) return true;
	return data.chain_name.includes(value);
};

let data: Tree[] = ref([]);
let firstNode = ref();

const getChainList = async () => {
	let res = await getList();
	console.log(props.hasAll)
	if (props.hasAll) {
		res.data.data.unshift({id:'',chain_name:'不限',isLeaf:true})
	}
	data.value = res.data.data;
	firstNode.value = data.value[0].id;
	changeChain(data.value[0], { level: 1 });
};

const loadChain = async (node: Node, resolve: (data: Tree[]) => void) => {
	if (node.level != 1) {
		resolve(
			node.data.children
				? node.data.children.map((i) => {
						i.isLeaf = i.children ? false : true;
						return i;
				  })
				: []
		);
		return;
	}
	let res = await getDetail({ id: node.data.id });
	const data: Tree[] = res.data[0].children.map((i) => {
		i.isLeaf = i.children ? false : true;
		return i;
	});
	resolve(data);
};

const changeChain = (data, node) => {
	emit('changeChain', data);
};

// 页面加载时
onMounted(() => {
	getChainList();
});
</script>
<style lang="scss" scoped>
::v-deep .is-current {
	color: #138af2;
}
::v-deep .el-tree-node__content {
	height: 35px;
	font-size: 16px;
}
::v-deep .el-tree-node__expand-icon {
	font-size: 16px;
}
::v-deep .el-input--large .el-input__wrapper {
	border-radius: 15px;
}
::v-deep .card-header {
	height: 35px;
	.icon {
		float: left;
		margin-right: 15px;
	}
	.title {
		font-size: 22px;
		color: #010101;
		float: left;
	}
	.remind {
		height: 16px;
		background: #ff0000;
		border-radius: 6px 6px 6px 0px;
		float: left;
		color: #ffff;
		margin-left: 10px;
		text-align: center;
		padding: 0px 5px;
		font-size: 12px;
	}
	.more {
		background-image: url('/src/assets/more.png');
		width: 16px;
		height: 14px;
		float: right;
		margin-top: 10px;
		background-size: 100% 100%;
	}
}

.list_div {
	height: calc(100% - 50px);
	overflow-y: auto;
	overflow-x: hidden;
}
</style>
